<?php

namespace app\Modules\Api\models;

use Yii;
use yii\base\Model;
/**
 * LoginForm is the model behind the login form.
 *
 * @property user|null $user This property is read-only.
 *
 */
class LoginForm extends Model
{
    public $name;
    public $pwd;
    public $phone_type;

    private $_user = false;

    public function attributeLabels()
    {
        return [
            'name'=>'用户名',
            'pwd'=>'密码',
            'phone_type'=>'手机类型',
        ];
    }

    /**
     * @return array the validation rules.
     */
    public function rules()
    {
        return [
            // username and password are both required
            [['name', 'pwd','phone_type'], 'required'],
            ['phone_type','in','range'=>[User::PHONE_TYPE_LEAVE,User::PHONE_TYPE_IOS,User::PHONE_TYPE_ANDROID]],
            // password is validated by validatePassword()
            ['pwd', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params)
    {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->pwd)) {
                $this->addError($attribute, '用户名或密码错误');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login()
    {
        if ($this->validate()) {
            return true;
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|false
     */
    public function getUser()
    {
        if ($this->_user === false) {
            $this->_user = User::find()->where(
                ['and',
                    ['or',
                        ['name'=>$this->name],
                        ['tele'=>$this->name]
                    ],
                    ['type'=>User::IS_USER]
                ]
            )->one();
        }

        return $this->_user;
    }
}